package com.common.secretkey;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordEncryptionExample {
    // 用于将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        return result.toString();
    }

    // 使用 SHA-256 算法对密码进行哈希处理
    private static String hashPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashedBytes = digest.digest(password.getBytes());
        return bytesToHex(hashedBytes);
    }

    // 比对用户输入的密码与数据库中存储的哈希值是否匹配
    private static boolean comparePasswords(String inputPassword, String storedHashedPassword)
            throws NoSuchAlgorithmException {
        String inputHashedPassword = hashPassword(inputPassword);
        return inputHashedPassword.equals(storedHashedPassword);
    }

    public static void main(String[] args) {
        try {
            // 假设从数据库中取得的存储的密码哈希值
            String storedHashedPassword = "6f3d5be14c4e27c334f2e8cfd2859ed578cd57a935ee8f9187450dc4798863fd";

            // 用户登录时提供的密码
            String userInputPassword = "password123";

            // 对用户输入的密码进行哈希处理，与数据库中的哈希值进行比对
            boolean passwordMatched = comparePasswords(userInputPassword, storedHashedPassword);

            System.out.println(hashPassword(userInputPassword));
            if (passwordMatched) {
                System.out.println("密码匹配，登录成功。");
            } else {
                System.out.println("密码不匹配，登录失败。");
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


    }
}
